<template>
  <div>
    <FormPanel ref="form" :list="formList" :labelPosition="'top'" :labelWidth="130" :cols="3" :isSubmitBtn="false" :collapse="false" />
    <FilterTable
      ref="table"
      :columns="columns"
      :dataSource="tableList"
      :isMemoryPagination="true"
      :isSelectColumn="false"
      height="auto"
      :onColumnsChange="(columns) => (this.columns = columns)"
    ></FilterTable>
    <FormPanel
      ref="formInfo"
      v-show="rowData.customersType == 21081002 || rowData.customersType == 21081003"
      :list="formListInfo"
      :labelPosition="'top'"
      :labelWidth="130"
      :cols="3"
      :isSubmitBtn="false"
      :collapse="false"
    />
    <div style="height: 47px"></div>
    <div class="footer">
      <el-button v-if="type === 'examine'" type="primary" :disabled="ischange" @click="closeDrawer('pass')">审核通过</el-button>
      <el-button v-if="type === 'examine'" type="primary" :disabled="ischange" @click="closeDrawer('reject')">审核驳回</el-button>
      <el-button @click="closeDrawer()">关 闭</el-button>
    </div>
  </div>
</template>
<script>
import { dictionary } from '@/utils/dictMixin';
import config from '@/assets/js/config';
import { getDetail, queryAllSeries, queryAllModelBySeries, rejectBigCustomer, passBigCustomer } from '@/api/omSaleP/KeyCustomers/KeyCustomerInfoVerify/index.js';
import { confirmAction } from '@/utils';
import moment from 'moment';
export default {
  props: {
    type: {
      type: String,
      require: true,
    },
    rowData: {
      type: Object,
    },
  },
  data() {
    return {
      formList: this.createdFrom(),
      formListInfo: this.createdInfoFrom(),
      followUpFormList: [
        {
          type: 'BREAK_SPACE',
          label: '大客户跟进信息',
        },
      ],
      columns: this.createdTable(),
      tableList: [],
      ischange: false,
      isAddDetail: false,
      addDetailType: 'demand',
      addRormData: {},
      datailData: {},
      current: null,
      demandSeries: [],
      demandModel: [],
    };
  },
  created() {
    //初始化省份数据
    this.initProvince();
    // 禁用
    this.formList.forEach((x) => {
      if (x.type !== 'BREAK_SPACE') {
        x.disabled = true;
      }
    });
    if (this.type === 'detail') {
      this.formListInfo.forEach((x) => {
        if (x.type !== 'BREAK_SPACE') {
          x.disabled = true;
        }
      });
    }
  },
  mounted() {
    this.table = this.$refs.table.$refs.pageTable;
    //获取所有车系数据
    this.queryAllSeries();
    //初始化页面
    if (this.rowData.id) {
      this.init();
    }
  },
  mixins: [dictionary],
  methods: {
    //初始化页面数据
    async init() {
      const res = await getDetail({ bigCustomerId: this.rowData.id });
      let data = {};
      if (res.resultCode === 200) {
        data = res.data;
        this.datailData = res.data;
      }
      this.formList.map(async (x) => {
        if (x.attachmentType) {
          data[x.fieldName].forEach((item) => {
            item.name = item.attachmentName;
            item.url = item.attachmentUrl;
            item.uid = item.attachmentUuid;
          });
        }
        if (data.provinceId) {
          await this.initCity(data.provinceId);
        }
        if (data.cityId) {
          await this.initRegion(data.cityId);
        }
        x.initialValue = data[x.fieldName];
        if (data.status === 21461003) {
          x.disabled = true;
        }
      });
      this.formListInfo.map((x) => {
        if ((x.fieldName = 'startDate|endDate')) {
          if (data.startDate && data.endDate) {
            x.initialValue = [data.startDate, data.endDate];
          }
        }
      });
      this.tableList = data.demandList;
      this.tableList.forEach(async (item) => {
        item.demandSeriesName = this.getName(this.demandSeries, item.demandSeriesId);
        await this.queryAllModelBySeries(item.demandSeriesId);
        item.demandModelName = this.getName(this.demandModel, item.demandModelId);
        this.$forceUpdate();
      });
    },
    // 获取所有车系
    async queryAllSeries() {
      const res = await queryAllSeries();
      if (res.resultCode === 200) {
        this.demandSeries = res.data.map((y) => ({ text: y.seriesName, value: y.seriesId }));
      }
    },
    //根据车系id查询车型
    async queryAllModelBySeries(id) {
      if (id) {
        const res = await queryAllModelBySeries({ pageNum: id });
        if (res.resultCode === 200) {
          this.demandModel = res.data.map((y) => ({ text: y.modelName, value: y.modelId }));
        }
      }
    },
    // 获取车系、车型名称
    getName(list, id) {
      const filterList = list.filter((item) => item.value === id);
      if (filterList.length > 0) {
        return filterList[0].text;
      }
      return '';
    },
    //保存， 提交, 关闭
    async closeDrawer(type = 'close') {
      if (type === 'close') {
        this.$emit('close');
        return;
      }
      let [err, data] = await this.$refs.formInfo.GET_FORM_DATA();
      if (err) return;
      data = { ...this.rowData, ...this.datailData, ...data };
      let facth = null;
      if (type === 'reject') {
        await this.$confirm('是否确认审核驳回大客户报备', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(async () => {
            facth = rejectBigCustomer;
          })
          .catch(() => {});
      }
      if (type === 'pass') {
        await this.$confirm('是否确认审核通过大客户报备', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(async () => {
            facth = passBigCustomer;
          })
          .catch(() => {});
      }
      if (facth !== null) {
        const resSave = await facth(data);
        if (resSave.resultCode === 200) {
          this.ischange = true;
          this.$notify.success({ title: '提示信息', message: `审核${type === 'reject' ? '驳回' : '通过'}成功` });
        } else {
          this.ischange = false;
          return;
        }
        this.$emit('close');
      }
    },
    //初始化所在省份
    async initProvince() {
      let pl = await this.createRegionsList();
      this.formList.find((item) => item.fieldName == 'provinceId').itemList = pl;
    },
    //初始化所在市数据
    async initCity(provinceId) {
      //清空市
      this.clearFormItem(this.formList.find((item) => item.fieldName == 'cityId'));
      this.clearFormItem(this.formList.find((item) => item.fieldName == 'districtId'));
      if (!provinceId || provinceId == null || typeof provinceId == 'undefined') {
        return;
      }
      //取城市数据
      let rd = this.createcityList(provinceId);
      this.formList.find((item) => item.fieldName == 'cityId').itemList = rd;
    },
    // 获取区县
    async initRegion(regionId) {
      this.clearFormItem(this.formList.filter((x) => x.fieldName === 'districtId')[0]);
      if (!regionId) return;
      let rd = this.district(regionId);
      this.formList.find((item) => item.fieldName == 'districtId').itemList = rd;
    },
    // 清除
    clearFormItem(item) {
      item.initialValue = undefined;
      item.itemList = [];
    },
    createdFrom() {
      return [
        {
          type: 'BREAK_SPACE',
          label: '大客户基础信息',
        },
        {
          type: 'INPUT',
          label: '大客户编号',
          fieldName: 'customersNo',
          disabled: true,
        },
        {
          type: 'SELECT',
          label: '大客户来源',
          fieldName: 'customersType',
          disabled: true,
          itemList: this.createDictList('2108'),
        },
        {
          type: 'SELECT',
          label: '大客户类型',
          disabled: true,
          fieldName: 'customerType',
          initialValue: 21171002,
          itemList: this.createDictList('2117'),
        },
        {
          type: 'INPUT',
          label: '大客户名称',
          rules: [{ required: true, message: '请输入', trigger: 'blur' }],
          fieldName: 'customersName',
        },
        {
          type: 'INPUT',
          label: '运营单位联系人',
          rules: [{ required: true, message: '请输入', trigger: 'blur' }],
          fieldName: 'contactsName',
        },
        {
          type: 'INPUT',
          label: '运营单位联系电话',
          rules: [{ required: true, message: '请输入', trigger: 'blur' }],
          fieldName: 'customerPhone',
        },
        {
          type: 'SELECT',
          label: '省份',
          rules: [{ required: true, message: '请选择', trigger: 'change' }],
          fieldName: 'provinceId',
          initialValue: '',
          itemList: [],
          change: (val) => {
            this.initCity(val);
          },
        },
        {
          type: 'SELECT',
          label: '城市',
          rules: [{ required: true, message: '请选择', trigger: 'change' }],
          fieldName: 'cityId',
          initialValue: '',
          itemList: [],
          change: (val) => {
            this.initRegion(val);
          },
        },
        {
          type: 'SELECT',
          label: '县区',
          fieldName: 'districtId',
          placeholder: '',
          initialValue: '',
          itemList: [],
        },
        {
          type: 'INPUT',
          label: '联系地址',
          rules: [{ required: true, message: '请输入', trigger: 'blur' }],
          maxlength: 36,
          fieldName: 'addressName',
          placeholder: '',
        },
        {
          type: 'SELECT',
          label: '证件类型',
          fieldName: 'credentialsType',
          disabled: true,
          initialValue: 21201008,
          itemList: this.createDictList('2120'),
        },
        {
          type: 'INPUT',
          label: '证件号',
          fieldName: 'credentialsNo',
        },
        {
          type: 'INPUT',
          label: '法人代表姓名',
          fieldName: 'legalPersonName',
        },
        {
          type: 'INPUT',
          label: '法人身份证号',
          fieldName: 'legalPersonIdCard',
        },
        {
          type: 'INPUT',
          label: '法人代表手机',
          fieldName: 'legalPersonMobile',
        },
        {
          type: 'INPUT',
          label: '授权人身份证号',
          fieldName: 'authorizationPersonIdCard',
        },
        {
          type: 'INPUT',
          label: '传真',
          fieldName: 'fax',
        },
        {
          type: 'INPUT',
          label: '邮编',
          fieldName: 'zipCode',
        },
        {
          type: 'BREAK_SPACE',
          label: '',
        },
        {
          type: 'UPLOAD_FILE',
          label: '法人身份证正面',
          fieldName: 'legalPersonIdCodeFrontList',
          placeholder: '请上传法人身份证正面',
          attachmentType: 11131001,
          selfCols: 1,
          initialValue: [],
          // rules: [{ required: true, message: '请上传法人身份证正面', trigger: 'change' }],
          upload: {
            actionUrl: `${config.uploadUrl}/api/file/oss/upload`,
            fixedSize: [5, 3],
            limit: 1,
            isCalcHeight: true,
          },
        },
        {
          type: 'UPLOAD_FILE',
          label: '法人身份证反面',
          fieldName: 'legalPersonIdCodeReverseList',
          attachmentType: 11131002,
          placeholder: '请上传法人身份证反面',
          selfCols: 1,
          initialValue: [],
          // rules: [{ required: true, message: '请上传法人身份证反面', trigger: 'change' }],
          upload: {
            actionUrl: `${config.uploadUrl}/api/file/oss/upload`,
            fixedSize: [5, 3],
            limit: 1,
            isCalcHeight: true,
          },
        },
        {
          type: 'UPLOAD_FILE',
          label: '管理员授权文件',
          attachmentType: 11131003,
          fieldName: 'administratorAuthorizationFileList',
          placeholder: '请上传管理员授权文件',
          selfCols: 1,
          initialValue: [],
          // rules: [{ required: true, message: '请上传管理员授权文件', trigger: 'change' }],
          upload: {
            actionUrl: `${config.uploadUrl}/api/file/oss/upload`,
            fixedSize: [5, 3],
            limit: 1,
            isCalcHeight: true,
          },
        },
        {
          type: 'UPLOAD_FILE',
          label: '授权人身份证正面',
          attachmentType: 11131004,
          fieldName: 'authorizationIdCardFrontList',
          placeholder: '请上传授权人身份证正面',
          selfCols: 1,
          initialValue: [],
          // rules: [{ required: true, message: '请上传授权人身份证正面', trigger: 'change' }],
          upload: {
            actionUrl: `${config.uploadUrl}/api/file/oss/upload`,
            fixedSize: [5, 3],
            limit: 1,
            isCalcHeight: true,
          },
        },
        {
          type: 'UPLOAD_FILE',
          label: '授权人身份证反面',
          attachmentType: 11131005,
          fieldName: 'authorizationIdCardReverseList',
          placeholder: '请上传授权人身份证反面',
          selfCols: 1,
          initialValue: [],
          // rules: [{ required: true, message: '请上传授权人身份证反面', trigger: 'change' }],
          upload: {
            actionUrl: `${config.uploadUrl}/api/file/oss/upload`,
            fixedSize: [5, 3],
            limit: 1,
            isCalcHeight: true,
          },
        },
        {
          type: 'UPLOAD_FILE',
          label: '营业执照',
          fieldName: 'businessLicenseList',
          attachmentType: 11131006,
          placeholder: '请上传营业执照',
          selfCols: 1,
          initialValue: [],
          // rules: [{ required: true, message: '请上传营业执照', trigger: 'change' }],
          upload: {
            actionUrl: `${config.uploadUrl}/api/file/oss/upload`,
            fixedSize: [5, 3],
            limit: 1,
            isCalcHeight: true,
          },
        },
        {
          type: 'BREAK_SPACE',
          label: '大客户需求信息',
        },
      ];
    },
    createdTable() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          fixed: 'left',
          render: (props) => {
            return <span>{props.row.index + 1}</span>;
          },
        },
        {
          title: '需求车系',
          dataIndex: 'demandSeriesId',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: (p) => {
            return <span>{p.row.demandSeriesName}</span>;
          },
        },
        {
          title: '需求车型',
          dataIndex: 'demandModelId',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: (p) => {
            return <span>{p.row.demandModelName}</span>;
          },
        },
        {
          title: '需求数量',
          dataIndex: 'demandNum',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '预计采购时间',
          dataIndex: 'expectPurchaseDate',
          sorter: true,
          filter: true,
          filterType: 'date-range',
          dateFormat: 'yyyy-MM-dd',
        },
        {
          title: '采购方式',
          dataIndex: 'purchaseType',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: (p) => {
            return <span>{this.createDictText(p.row.purchaseType, '2142')}</span>;
          },
        },
        {
          title: '预计采购价格',
          dataIndex: 'expectPurchasePrice',
          sorter: true,
          filter: true,
          precision: 2,
          numberFormat: true,
          align: 'right',
          filterType: 'input',
        },
        {
          title: '市场指导价',
          dataIndex: 'marketDirectivePrice',
          sorter: true,
          filter: true,
          precision: 2,
          numberFormat: true,
          align: 'right',
          filterType: 'input',
        },
      ];
    },
    createdInfoFrom() {
      return [
        {
          type: 'BREAK_SPACE',
          label: '大客户审核信息',
        },
        {
          type: 'RANGE_DATE',
          label: '报备有效时间',
          fieldName: 'startDate|endDate',
          placeholder: '请选择日期',
          dateType: 'exactdaterange',
          initialValue: this.type === 'examine' ? [moment().format('YYYY-MM-DD'), moment().add(3, 'months').format('YYYY-MM-DD')] : [],
          format: 'yyyy-MM-dd',
          rules: [{ required: true, message: '请选择日期', trigger: 'change' }],
        },
      ];
    },
  },
};
</script>
<style lang="scss">
.footer {
  position: 'absolute';
  left: 0;
  bottom: 0;
  right: 0;
  z-index: 9;
  border-top: '1px solid #e9e9e9';
  padding: '10px 20px';
  background: '#fff';
  text-align: 'right';
  padding: 20px 30%;
  box-sizing: border-box;
  display: flex;
  justify-content: space-around;
}
.upload-btn {
  width: 100%;
}
.el-upload-list__item-name {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  width: 100%;
  padding-right: 20px;
  box-sizing: border-box;
}
</style>